<template>
  <div class="article-list" ref="articleList" @scroll="scrollEvent">
    <van-pull-refresh v-model="isLoading" @refresh="refresh">
      <van-list
        v-if="bol"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="getArticle"
      >
        <ArticleItem
          v-for="item in articlesList"
          :key="item.id"
          :item="item"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from './article-item.vue'
import { articles } from '@/api/home.js'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: ['id'],
  data () {
    return {
      timestamp: Date.now(),
      articlesList: [],
      loading: false,
      finished: false,
      isLoading: false,
      bol: true,
      scrollTop: 0
    }
  },
  methods: {
    async getArticle () {
      const res = await articles({
        channel_id: this.id,
        timestamp: this.timestamp
      })
      this.articlesList.push(...res.data.results)
      this.loading = false
      if (res.data.pre_timestamp) {
        this.timestamp = res.data.pre_timestamp
      } else {
        this.finished = true
      }
    },
    refresh () {
      this.timestamp = Date.now()
      this.articlesList = []
      this.loading = false
      this.finished = false
      this.isLoading = false
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    },
    scrollEvent () {
      this.scrollTop = this.$refs.articleList.scrollTop
    }
  },
  activated () {
    this.$refs.articleList.scrollTop = this.scrollTop
  }
}
</script>

<style lang="less" scoped>
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
